import { asyncRouterMap, constantRouterMap } from '@/router'
import store from '@/store';
import zh from '@/lang/zh.js'


let testRouterPath=[];

function findeName(name){
  let zhArry=zh.route;
  return zhArry[name]
}

let routerArry = [];
function formatUserRouter (userRouter = []) {
  userRouter.map(item => {
    if (item.type === 'MENU') {
      routerArry.push({
        menuPath: item.menuPath,
        name: item.name,
      })
    }
    if (item.children && item.children.length > 0) {
      formatUserRouter(item.children)
    }
  })
  return routerArry;
}
function filter (router = [], item = {}) {
  let targeIsExist = false;
  if (item.alwaysShow || item.path == '*' || item.hidden == true) {
    targeIsExist = true;
  } else {
    router.map(targe => {
      let pathArry = targe.menuPath.split('/')
      let path = pathArry[pathArry.length - 1]
      if (path == item.path) {
        //TODO 测试菜单代码 start
        testRouterPath.push({
          "权限地址:":targe.menuPath,
          "本地匹配地址:":item.path,
          "权限菜单名:":targe.name,
          "本地菜单名:":findeName(item.name),
        })
        //TODO 测试菜单代码 end
        targeIsExist = true;
      }
    })
  }
  return targeIsExist;
}
function recursionRouter (router = [], asyncRouterMap = []) {
  let realRoutes = [];
  asyncRouterMap.map(item => {
    if (item.children && item.children.length > 0) {
      let list = recursionRouter(router, item.children);
      item.children = isAllNotHiddenRouter(list) ? list : []
    }
    if (filter(router, item)) {
      realRoutes.push(item)
    }
  })
  return realRoutes
}
function isAllNotHiddenRouter (childrenList = []) {
  let tage = false;
  childrenList.map(item => {
    if (!("hidden" in item)) {
      tage = true
    }
  })
  return tage
}
function filterAccessedRoutes (router = []) {
  return router.filter(item => {
    if (item.children && item.children.length > 0) {
      let list = filterAccessedRoutes(item.children)
      item.children = isAllNotHiddenRouter(list) ? list : []
    }
    if (!item.children || item.children.length > 0) {
      return item
    }
  })
}
const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    generateRoutes ({ commit }, roles) {
      return new Promise(resolve => {
        const { account } = store.getters.userInfo
        let accessedRoutes = account == 'admin' ? asyncRouterMap : filterAccessedRoutes(recursionRouter(formatUserRouter(roles), [...asyncRouterMap]));
        // console.table(testRouterPath)
        commit('SET_ROUTERS', accessedRoutes)
        resolve(accessedRoutes)
      })
    }
  }
}

export default permission
